#include <kwdb/client.h>
#include <iostream>
#include <chrono>
#include <cstdlib>

int main() {
    // Test with timeout configuration
    kwdb::IngestConfig config;
    config.ingest_endpoint = "127.0.0.1:9090";
    config.timeout_ms = 1000; // 1 second timeout

    kwdb::KwdbClient client(config);

    kwdb::Point point("timeout_test");
    point.add_tag("host", "test");
    point.add_field("value", 42.0);

    auto start = std::chrono::steady_clock::now();
    auto status = client.write(point);
    auto end = std::chrono::steady_clock::now();
    auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();

    // Check if INJECT_DELAY_MS is set to actually test timeout
    const char* delay_env = std::getenv("INJECT_DELAY_MS");
    bool should_timeout = (delay_env && std::atoi(delay_env) > config.timeout_ms);

    if (should_timeout) {
        // Delay injection enabled - expect timeout
        if (!status.ok()) {
            std::cout << "PASS: Timeout triggered after " << duration_ms << "ms" << std::endl;
            std::cout << "Error message: " << status.message << std::endl;
            if (status.message.find("Deadline") != std::string::npos ||
                status.message.find("deadline") != std::string::npos ||
                status.message.find("timeout") != std::string::npos) {
                std::cout << "✅ Deadline/timeout detected correctly!" << std::endl;
                return 0;
            }
        }
        std::cout << "FAIL: Should have timed out with INJECT_DELAY_MS=" << delay_env << "ms" << std::endl;
        return 1;
    } else {
        // Normal mode - just verify write succeeds with timeout configured
        if (status.ok()) {
            std::cout << "✅ PASS: Write succeeded within timeout (" << duration_ms << "ms)" << std::endl;
            std::cout << "NOTE: To test actual timeout behavior, run with INJECT_DELAY_MS=2000" << std::endl;
            return 0;
        } else {
            std::cout << "FAIL: Write failed unexpectedly: " << status.message << std::endl;
            return 1;
        }
    }
}